clear
set more off

cap log close
log using $logdir/delta_gr.log, replace

use tp delta_gr ertc ertc_amendment firm_id wg_amt ///
    using $fromsasdir/result if !missing(delta_gr) & tp < 202112 , clear
drop if ertc > 900*10^6
gen post = tp >= 202103
qui replace ertc = ertc + ertc_amendment
gcollapse delta_gr (sum) ertc wg_amt, by(firm_id post) fast

gen bin = 0
qui replace bin = 1 if delta_gr >= -0.8
qui replace bin = 2 if delta_gr >= -0.6
qui replace bin = 3 if delta_gr >= -0.4
qui replace bin = 4 if delta_gr >= -0.2
qui replace bin = 5 if delta_gr >= 0
qui replace bin = 6 if delta_gr >= 0.25
qui replace bin = 7 if delta_gr >= 1


gcollapse (max) max_ertc = ertc max_wg = wg_amt (sum) ertc wg_amt, by(bin post) fast

gen ratio_ertc = max_ertc/ertc
gen ratio_wg = max_wg/wg_amt

qui sum ratio_ertc
assert r(max) <= 0.4

qui sum ratio_wg
assert r(max) <= 0.4


sort post
foreach var in ertc wg_amt {
    by post: egen tot_`var' = sum(`var')
    gen share_`var' = `var'/tot_`var'
}
keep bin post share_*
sort post bin
list

qui save $outdir/delta_gr, replace




cap log close